#include "SoundManager.h"
#include "ReportError.h"
#include "LoadScreen.h"
#include <assert.h>


SoundManager::SoundManager()
{
	int audio_rate = 22050;
	Uint16 audio_format = AUDIO_S16SYS;
	int audio_channels = 2;
	int audio_buffers = 4096;
	m_isMuted = false;

	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) !=0)
	{

	}
}

bool SoundManager::Load(const std::string& effFile, const std::string& musFile)
{
	File f;
	File g;
 	if(!f.OpenRead(effFile))
 	{
 		ReportError("Sound file paths not found");
 	}
	
	if(!LoadSoundEffect(&f))
	{
		ReportError("'SoundManager::LoadSoundEffect(File*)' Failed)");
	}

	

	if(!g.OpenRead(musFile))
	{
		ReportError("music filepath not found");
	}
	
	if(!LoadMusic(&g))
	{
		ReportError("'SoundManager::LoadMusic(File*)' Failed");
	}

	
	return true;
}

bool SoundManager::LoadSoundEffect(File* const f)
{
	std::string str;
	int effectNum;
	if(!f->GetString(&str))
	{
		ReportError("soundeffect filename not found");
	}
	if(!f->GetInteger(&effectNum))
	{
		ReportError("soundeffect name not found");
	}
	Mix_Chunk* sound = Mix_LoadWAV(str.c_str());
	assert(sound);
	m_soundEffects.insert(std::pair<int, Mix_Chunk*>(effectNum, sound));
	return true;
}

bool SoundManager::LoadMusic(File* const f)
{
	std::string str;
	int trackNum;
	if(!f->GetString(&str))
	{
		ReportError("Music filename not found");
		return false;
	}
	if(!f->GetInteger(&trackNum))
	{
		ReportError("tracknumber not found");
		return false;
	}
	Mix_Music* mus = Mix_LoadMUS(str.c_str());
	assert(mus);
	m_musicTracks.insert(std::pair<int, Mix_Music*>(trackNum, mus));
	return true;
}

bool SoundManager::SoundEffectPlay(int effectId)
{
	if(!m_isMuted)
	{
		assert(m_soundEffects.size());
		m_it = m_soundEffects.find(effectId);
		int channel = Mix_PlayChannel(-1, m_it->second, 0);
		//Mix_SetPanning(channel,255, 127);
	}
	return true;
}
bool SoundManager::MusicPlay(int trackNum, bool loop)
{
	if(!m_isMuted)
	{
		assert(m_musicTracks.size());
		m_jt = m_musicTracks.find(trackNum);
		if (loop)
		{
			Mix_PlayMusic(m_jt->second, -1);
		}
		else
		{
			Mix_PlayMusic(m_jt->second, 0);
		}
	}
	return true;
}

void SoundManager::Mute()
{
	m_isMuted = true;
}

void SoundManager::UnMute()
{
	m_isMuted = false;
}

void SoundManager::EnableEffects()
{
	
}